package ext.generic.part;

import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.util.Locale;

import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.iba.definition.AbstractAttributeDefinition;
import wt.iba.definition.SoftMetaData;
import wt.iba.definition.litedefinition.AttributeDefDefaultView;
import wt.iba.definition.litedefinition.StringDefView;
import wt.iba.definition.service.IBADefViewManager;
import wt.iba.value.DefaultAttributeContainer;
import wt.iba.value.IBAHolder;
import wt.iba.value.litevalue.AbstractValueView;
import wt.iba.value.litevalue.FloatValueDefaultView;
import wt.iba.value.litevalue.IntegerValueDefaultView;
import wt.iba.value.litevalue.StringValueDefaultView;
import wt.iba.value.litevalue.TimestampValueDefaultView;
import wt.iba.value.litevalue.URLValueDefaultView;
import wt.iba.value.litevalue.UnitValueDefaultView;
import wt.iba.value.service.IBAValueHelper;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.part.WTPart;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;

import com.ptc.core.meta.server.impl.LogicalIdentifierMapEntry;

import ext.com.core.CoreUtil;

public class CusIBAUtil implements RemoteAccess{
	private static final boolean VERBOSE = true ;
	
	private static final String CLASSNAME = CusIBAUtil.class.getName() ;
	
	/**
	 * 设置多值枚举类型IBA属性
	 * @param ibaHolder 对象
	 * @param ibaLogicalId IBA属性逻辑标示符
	 * @param value 枚举值的内部值，多个值之间用逗号分隔 
	 * @return
	 * @throws WTException
	 * 
	 * shell下运行，例如：C:\ptc\Windchill_10.1\Windchill>windchill ext.generic.part.CusIBAUtil 0000000562 Design C10,A10,B10,D10
	 */
	public static IBAHolder forceSetEnumIBAValue(IBAHolder ibaHolder, String ibaLogicalId, Object value) throws WTException {
		if (VERBOSE){
			System.out.println(">>>" + CLASSNAME + ".forceSetIBAValue()---ibaLogicalId=" + ibaLogicalId + "; value=" + value);
		}
		
		if (ibaHolder == null){
			return ibaHolder;
		}
		
		Locale locale = SessionHelper.getLocale();
		
		try {
			ibaHolder = IBAValueHelper.service.refreshAttributeContainer(ibaHolder, null, locale, null);

			if (ibaHolder.getAttributeContainer() == null) {
				ibaHolder = IBAValueHelper.service.refreshAttributeContainer(ibaHolder, null, locale, null);
				
				if (ibaHolder.getAttributeContainer() == null) {
					ibaHolder.setAttributeContainer(new DefaultAttributeContainer());
				}
			}
		} catch (Exception e) {
			ibaHolder.setAttributeContainer(new DefaultAttributeContainer());
		}

		// Fill IBA container
		DefaultAttributeContainer container = (DefaultAttributeContainer) (ibaHolder.getAttributeContainer());
		
		try {
			AttributeDefDefaultView ibaDefView = getAttDefViewByLogicalID(ibaLogicalId);

			container.deleteAttributeValues(ibaDefView);
			
			if (ibaDefView instanceof StringDefView) {
				String strValue = value.toString() ;
				
				String[] strValueArray = strValue.split(",");
				
				if( strValueArray != null){
					for(int i=0 ; i < strValueArray.length ; i++ ){
						if( strValueArray[i] != null  ){
							strValueArray[i] = strValueArray[i].trim();
							if( !strValueArray[i].equals("") ){
								AbstractValueView ibaValueView = new StringValueDefaultView((StringDefView) ibaDefView , strValueArray[i]);
								
								container.addAttributeValue(ibaValueView);
								
								if (VERBOSE){
									System.out.println("   >>>> Add IBA Values...");
								}
							}																	
						}
					}
				}			
				
			} 
			
			ibaHolder.setAttributeContainer(container);
			ibaHolder = wt.iba.value.service.LoadValue.applySoftAttributes(ibaHolder);
		} catch (Exception exp) {
			throw new WTException(exp);
		}

		return ibaHolder;
	}
	
	/**
	 *根据IBA的逻辑标识符获取其属性定义
	 * @param logicalId IBA的逻辑标识符
	 * @return AttributeDefDefaultView IBA属性定义视图对象
	 * @throws Exception
	 */
	public static AttributeDefDefaultView getAttDefViewByLogicalID(String logicalId) throws WTException {
		if (VERBOSE){
			System.out.println(">>>" + CLASSNAME + ".getAttDefViewByLogicalID()---logicalId=" + logicalId);
		}
		
		//首先搜索逻辑标识符对象
		LogicalIdentifierMapEntry logicalIdentifier = null;
		AbstractAttributeDefinition attributeDef = null;
		AttributeDefDefaultView defView = null;

		QuerySpec qs = new QuerySpec(LogicalIdentifierMapEntry.class);
		SearchCondition sc = new SearchCondition(LogicalIdentifierMapEntry.class, LogicalIdentifierMapEntry.LOGICAL_IDENTIFIER, SearchCondition.EQUAL, logicalId);
		qs.appendSearchCondition(sc);
		QueryResult qr = PersistenceHelper.manager.find(qs);

		while (qr.hasMoreElements()) {
			logicalIdentifier = (LogicalIdentifierMapEntry) qr.nextElement();
			SoftMetaData softMetaData = logicalIdentifier.getIdentifiedObject();
			if (softMetaData instanceof AbstractAttributeDefinition) {
				attributeDef = (AbstractAttributeDefinition) softMetaData;
				break;
			}
		}
		
		if (VERBOSE){
			System.out.println("    the AttributeDefinition=" + attributeDef);
		}
		
		//获取IBA属性定义视图
		if (attributeDef != null){
			defView = IBADefViewManager.getAttDefView(attributeDef);
		}
		
		return defView;
	}
	

	/**
	 *拷贝属性值
	 */
	private static AbstractValueView internalCopyValue(AbstractValueView source, AbstractValueView dest) throws WTPropertyVetoException {
		if (source instanceof StringValueDefaultView) {
			((StringValueDefaultView) source).setValue(((StringValueDefaultView) dest).getValue());
		} else if (source instanceof FloatValueDefaultView) {
			((FloatValueDefaultView) source).setValue(((FloatValueDefaultView) dest).getValue());
		} else if (source instanceof IntegerValueDefaultView) {
			((IntegerValueDefaultView) source).setValue(((IntegerValueDefaultView) dest).getValue());
		} else if (source instanceof URLValueDefaultView) {
			((URLValueDefaultView) source).setValue(((URLValueDefaultView) dest).getValue());
			((URLValueDefaultView) source).setDescription(((URLValueDefaultView) dest).getDescription());
		} else if (source instanceof TimestampValueDefaultView) {
			((TimestampValueDefaultView) source).setValue(((TimestampValueDefaultView) dest).getValue());
		} else if (source instanceof UnitValueDefaultView) {
			((UnitValueDefaultView) source).setValue(((UnitValueDefaultView) dest).getValue());
		}
		return source;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if( args != null && args.length != 3 ){
			System.out.println( "Debug   参数列表异常..." );
			return;
		}
		

		try {
			
			WTPart part = CoreUtil.getWTPartByNumberAndView(args[0], args[1]);
			if( part != null ){
				
				System.out.println( "Debug   partNumber:"+part.getNumber() );
				if (!RemoteMethodServer.ServerFlag) {
					System.out.println( "Debug    RemoteMethodServer..." );
					String method = "forceSetEnumIBAValue";
					
					RemoteMethodServer.getDefault().invoke(method, CLASSNAME , null,
								        new Class[] { IBAHolder.class ,String.class,Object.class}, new Object[] { part,"partValue",args[2] });
					
					System.out.println( "Debug    end  RemoteMethodServer..." );
				}else{
					System.out.println( "Debug   forceSetEnumIBAValue..." );
					forceSetEnumIBAValue(part,"partValue",args[2]);
					System.out.println( "Debug   end  forceSetEnumIBAValue..." );
				}
			}
		} catch (WTException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

	}
}
